package com.lotusfall.jdbc;

import java.sql.*;
import java.util.Scanner;

//
public class JDBCTest08 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.printf("输入desc或asc：desc表示降序，asc表示升序");
        System.out.println("请输入：");
        String keyword = s.nextLine();

        // 执行SQL
        Connection conn = null;
        // PreparedStatement ps = null;
        Statement ps = null;
        ResultSet rs = null;

        String loginName = "zhangsan";
        String loginPwd = "123";
        try {
            // 1、注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2、获取链接
            String url = "jdbc:mysql://127.0.0.1:3306/learn?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
            String user = "root";
            String password = "994695";
            conn = DriverManager.getConnection(url,user,password);

            // 3、获取预编译的数据库操作对象
            //String sql = "select ename from emp order by ename ?";  // 报错
            String sql = "select ename from emp order by ename " + keyword;
            // ps = conn.prepareStatement(sql);

            ps = conn.createStatement();
            rs = ps.executeQuery(sql);
            // 4、执行sql语句
            // 5、处理结果集
            while(rs.next()){
                System.out.println(rs.getString("ename"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
